import 'package:flutter/material.dart';
import 'package:accept_form/models/acceptance_category.dart';
import 'package:accept_form/models/user.dart';
import 'package:accept_form/services/acceptance_service.dart';
import 'package:accept_form/services/user_service.dart';

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  final _formKey = GlobalKey<FormState>();
  final _categoryFormKey = GlobalKey<FormState>();
  final _userFormKey = GlobalKey<FormState>();
  
  // 分类管理相关
  List<AcceptanceCategory> _categories = [];
  List<AcceptanceCategory> _mainCategories = [];
  AcceptanceCategory? _selectedMainCategory;
  final _categoryNameController = TextEditingController();
  final _sortOrderController = TextEditingController();
  bool _isSubCategory = false;
  
  // 用户管理相关
  List<User> _users = [];
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _realNameController = TextEditingController();
  final _emailController = TextEditingController();
  final _phoneController = TextEditingController();
  bool _isUserEditing = false;
  User? _editingUser;

  @override
  void initState() {
    super.initState();
    _loadCategories();
    _loadUsers();
  }

  @override
  void dispose() {
    _categoryNameController.dispose();
    _sortOrderController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _realNameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  Future<void> _loadCategories() async {
    final categories = await AcceptanceService.instance.getCategories();
    setState(() {
      _categories = categories;
      _mainCategories = categories.where((c) => c.level == 1).toList();
    });
  }

  Future<void> _loadUsers() async {
    final users = await UserService.instance.getUsers();
    setState(() {
      _users = users;
    });
  }

  void _showCategoryDialog({AcceptanceCategory? category}) {
    if (category != null) {
      _categoryNameController.text = category.name;
      _sortOrderController.text = category.sortOrder.toString();
      _isSubCategory = category.level == 2;
      _selectedMainCategory = _categories.firstWhere((c) => c.id == category.parentId);
    } else {
      _categoryNameController.clear();
      _sortOrderController.clear();
      _isSubCategory = false;
      _selectedMainCategory = null;
    }

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(category == null ? '添加分类' : '编辑分类'),
        content: Form(
          key: _categoryFormKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _categoryNameController,
                decoration: const InputDecoration(labelText: '分类名称'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入分类名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _sortOrderController,
                decoration: const InputDecoration(labelText: '排序'),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入排序';
                  }
                  if (int.tryParse(value) == null) {
                    return '请输入有效的数字';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              CheckboxListTile(
                title: const Text('是否为子分类'),
                value: _isSubCategory,
                onChanged: (value) {
                  setState(() {
                    _isSubCategory = value ?? false;
                  });
                },
              ),
              if (_isSubCategory) ...[
                const SizedBox(height: 16),
                DropdownButtonFormField<AcceptanceCategory>(
                  value: _selectedMainCategory,
                  decoration: const InputDecoration(labelText: '所属大类'),
                  items: _mainCategories.map((category) {
                    return DropdownMenuItem(
                      value: category,
                      child: Text(category.name),
                    );
                  }).toList(),
                  onChanged: (value) {
                    setState(() {
                      _selectedMainCategory = value;
                    });
                  },
                  validator: (value) {
                    if (_isSubCategory && value == null) {
                      return '请选择所属大类';
                    }
                    return null;
                  },
                ),
              ],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              if (_categoryFormKey.currentState!.validate()) {
                try {
                  if (category == null) {
                    await AcceptanceService.instance.createCategory(
                      name: _categoryNameController.text,
                      level: _isSubCategory ? 2 : 1,
                      parentId: _isSubCategory ? _selectedMainCategory!.id : null,
                      sortOrder: int.parse(_sortOrderController.text),
                    );
                  } else {
                    await AcceptanceService.instance.updateCategory(
                      id: category.id,
                      name: _categoryNameController.text,
                      level: _isSubCategory ? 2 : 1,
                      parentId: _isSubCategory ? _selectedMainCategory!.id : null,
                      sortOrder: int.parse(_sortOrderController.text),
                    );
                  }
                  if (mounted) {
                    Navigator.pop(context);
                    _loadCategories();
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('${category == null ? '添加' : '更新'}成功')),
                    );
                  }
                } catch (e) {
                  if (mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('操作失败: $e')),
                    );
                  }
                }
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showUserDialog({User? user}) {
    _isUserEditing = user != null;
    _editingUser = user;
    
    if (user != null) {
      _usernameController.text = user.username;
      _realNameController.text = user.name;
      _emailController.text = user.email ?? '';
      _phoneController.text = user.phone ?? '';
    } else {
      _usernameController.clear();
      _passwordController.clear();
      _realNameController.clear();
      _emailController.clear();
      _phoneController.clear();
    }

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(user == null ? '添加用户' : '编辑用户'),
        content: Form(
          key: _userFormKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _usernameController,
                decoration: const InputDecoration(labelText: '用户名'),
                enabled: !_isUserEditing,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  return null;
                },
              ),
              if (!_isUserEditing) ...[
                const SizedBox(height: 16),
                TextFormField(
                  controller: _passwordController,
                  decoration: const InputDecoration(labelText: '密码'),
                  obscureText: true,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入密码';
                    }
                    return null;
                  },
                ),
              ],
              const SizedBox(height: 16),
              TextFormField(
                controller: _realNameController,
                decoration: const InputDecoration(labelText: '真实姓名'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入真实姓名';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _emailController,
                decoration: const InputDecoration(labelText: '邮箱'),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  if (value != null && value.isNotEmpty && !value.contains('@')) {
                    return '请输入有效的邮箱地址';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(labelText: '手机号'),
                keyboardType: TextInputType.phone,
                validator: (value) {
                  if (value != null && value.isNotEmpty) {
                    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value) &&
                        !RegExp(r'^0\d{2,3}-?\d{7,8}$').hasMatch(value)) {
                      return '请输入有效的手机号或固定电话';
                    }
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              if (_userFormKey.currentState!.validate()) {
                try {
                  if (user == null) {
                    await UserService.instance.createUser(
                      username: _usernameController.text,
                      password: _passwordController.text,
                      realName: _realNameController.text,
                      email: _emailController.text,
                      phone: _phoneController.text,
                    );
                  } else {
                    await UserService.instance.updateUser(
                      id: user.id,
                      realName: _realNameController.text,
                      email: _emailController.text,
                      phone: _phoneController.text,
                    );
                  }
                  if (mounted) {
                    Navigator.pop(context);
                    _loadUsers();
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('${user == null ? '添加' : '更新'}成功')),
                    );
                  }
                } catch (e) {
                  if (mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('操作失败: $e')),
                    );
                  }
                }
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  Future<void> _deleteCategory(AcceptanceCategory category) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除分类"${category.name}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        await AcceptanceService.instance.deleteCategory(category.id);
        _loadCategories();
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('删除成功')),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('删除失败: $e')),
          );
        }
      }
    }
  }

  Future<void> _deleteUser(User user) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除用户"${user.name}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        await UserService.instance.deleteUser(user.id);
        _loadUsers();
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('删除成功')),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('删除失败: $e')),
          );
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('系统设置'),
          bottom: const TabBar(
            tabs: [
              Tab(text: '纠纷分类管理'),
              Tab(text: '用户管理'),
            ],
          ),
        ),
        body: TabBarView(
          children: [
            // 纠纷分类管理
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      ElevatedButton.icon(
                        onPressed: () => _showCategoryDialog(),
                        icon: const Icon(Icons.add),
                        label: const Text('添加分类'),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  Expanded(
                    child: ListView.builder(
                      itemCount: _categories.length,
                      itemBuilder: (context, index) {
                        final category = _categories[index];
                        return Card(
                          child: ListTile(
                            title: Text(category.name),
                            subtitle: Text(
                              '级别: ${category.level == 1 ? '大类' : '小类'}, '
                              '排序: ${category.sortOrder}',
                            ),
                            trailing: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                IconButton(
                                  icon: const Icon(Icons.edit),
                                  onPressed: () => _showCategoryDialog(category: category),
                                ),
                                IconButton(
                                  icon: const Icon(Icons.delete),
                                  onPressed: () => _deleteCategory(category),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
            // 用户管理
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      ElevatedButton.icon(
                        onPressed: () => _showUserDialog(),
                        icon: const Icon(Icons.add),
                        label: const Text('添加用户'),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  Expanded(
                    child: ListView.builder(
                      itemCount: _users.length,
                      itemBuilder: (context, index) {
                        final user = _users[index];
                        return Card(
                          child: ListTile(
                            title: Text(user.name),
                            subtitle: Text(
                              '用户名: ${user.username}, '
                              '邮箱: ${user.email ?? '未设置'}, '
                              '电话: ${user.phone ?? '未设置'}',
                            ),
                            trailing: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                IconButton(
                                  icon: const Icon(Icons.edit),
                                  onPressed: () => _showUserDialog(user: user),
                                ),
                                IconButton(
                                  icon: const Icon(Icons.delete),
                                  onPressed: () => _deleteUser(user),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
} 